import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表板' }
      },
      {
        path: 'articles',
        name: 'ArticleList',
        component: () => import('@/views/article/List.vue'),
        meta: { title: '文章列表' }
      },
      {
        path: 'articles/create',
        name: 'ArticleCreate',
        component: () => import('@/views/article/Edit.vue'),
        meta: { title: '创建文章' }
      },
      {
        path: 'articles/edit/:id',
        name: 'ArticleEdit',
        component: () => import('@/views/article/Edit.vue'),
        meta: { title: '编辑文章' }
      },
      {
        path: 'categories',
        name: 'CategoryList',
        component: () => import('@/views/category/List.vue'),
        meta: { title: '分类管理' }
      },
      {
        path: 'tags',
        name: 'TagList',
        component: () => import('@/views/tag/List.vue'),
        meta: { title: '标签管理' }
      },
      {
        path: 'article-flags',
        name: 'ArticleFlagList',
        component: () => import('@/views/articleFlag/List.vue'),
        meta: { title: '文章属性管理' }
      },
      {
        path: 'pages',
        name: 'PageList',
        component: () => import('@/views/page/List.vue'),
        meta: { title: '单页管理' }
      },
      {
        path: 'pages/create',
        name: 'PageCreate',
        component: () => import('@/views/page/Edit.vue'),
        meta: { title: '创建单页' }
      },
      {
        path: 'pages/edit/:id',
        name: 'PageEdit',
        component: () => import('@/views/page/Edit.vue'),
        meta: { title: '编辑单页' }
      },
      {
        path: 'media',
        name: 'MediaList',
        component: () => import('@/views/media/List.vue'),
        meta: { title: '媒体库' }
      },
      {
        path: 'build',
        name: 'StaticBuild',
        component: () => import('@/views/build/Index.vue'),
        meta: { title: '静态生成' }
      },
      {
        path: 'sitemap',
        name: 'SitemapIndex',
        component: () => import('@/views/sitemap/Index.vue'),
        meta: { title: 'Sitemap生成' }
      },
      {
        path: 'users',
        name: 'UserList',
        component: () => import('@/views/user/List.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'roles',
        name: 'RoleList',
        component: () => import('@/views/role/List.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: 'config',
        name: 'SystemConfig',
        component: () => import('@/views/config/Index.vue'),
        meta: { title: '基本信息' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人信息' }
      },
      {
        path: 'logs',
        name: 'OperationLogs',
        component: () => import('@/views/log/List.vue'),
        meta: { title: '操作日志' }
      },
      {
        path: 'recycle-bin',
        name: 'RecycleBin',
        component: () => import('@/views/RecycleBin.vue'),
        meta: { title: '回收站' }
      },
      {
        path: 'content-models',
        name: 'ContentModelList',
        component: () => import('@/views/contentModel/List.vue'),
        meta: { title: '内容模型' }
      },
      {
        path: 'custom-fields',
        name: 'CustomFieldList',
        component: () => import('@/views/customField/List.vue'),
        meta: { title: '自定义字段' }
      },
      {
        path: 'topics',
        name: 'TopicList',
        component: () => import('@/views/topic/List.vue'),
        meta: { title: '专题管理' }
      },
      {
        path: 'links',
        name: 'LinkList',
        component: () => import('@/views/link/List.vue'),
        meta: { title: '友情链接' }
      },
      {
        path: 'ads',
        name: 'AdList',
        component: () => import('@/views/ad/List.vue'),
        meta: { title: '广告管理' }
      },
      {
        path: 'sliders',
        name: 'SliderList',
        component: () => import('@/views/slider/List.vue'),
        meta: { title: '幻灯片管理' }
      },
      {
        path: 'seo-settings',
        name: 'SeoSettings',
        component: () => import('@/views/seo/Settings.vue'),
        meta: { title: 'SEO设置' }
      },
      {
        path: 'seo-redirects',
        name: 'SeoRedirect',
        component: () => import('@/views/seo/Redirect.vue'),
        meta: { title: 'URL重定向' }
      },
      {
        path: 'seo-404-logs',
        name: 'Seo404Log',
        component: () => import('@/views/seo/Log404.vue'),
        meta: { title: '404错误监控' }
      },
      {
        path: 'seo-robots',
        name: 'SeoRobots',
        component: () => import('@/views/seo/Robots.vue'),
        meta: { title: 'Robots.txt' }
      },
      {
        path: 'seo-tools',
        name: 'SeoTools',
        component: () => import('@/views/seo/Tools.vue'),
        meta: { title: 'SEO工具' }
      },
      {
        path: 'database',
        name: 'Database',
        component: () => import('@/views/system/Database.vue'),
        meta: { title: '数据库管理' }
      },
      {
        path: 'cache',
        name: 'Cache',
        component: () => import('@/views/system/Cache.vue'),
        meta: { title: '缓存管理' }
      },
      {
        path: 'system-logs',
        name: 'SystemLogs',
        component: () => import('@/views/system/Logs.vue'),
        meta: { title: '系统日志' }
      },
      {
        path: 'template-editor',
        name: 'TemplateEditor',
        component: () => import('@/views/template/Editor.vue'),
        meta: { title: '模板编辑器' }
      }
    ]
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 防止重复显示错误消息的标志
let isShowingAuthError = false

// 全局路由守卫 - 登录检查
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 逍遥内容管理系统` : '逍遥内容管理系统'

  const token = getToken()
  const userStore = useUserStore()

  // 白名单路由（不需要登录即可访问）
  const whiteList = ['/login']

  if (token) {
    // 已登录
    if (to.path === '/login') {
      // 如果已登录，访问登录页则跳转到首页
      next('/')
    } else {
      // 检查是否已获取用户信息
      if (!userStore.userInfo) {
        try {
          // 获取用户信息
          await userStore.getUserInfo()
          next()
        } catch (error) {
          // 获取用户信息失败，可能 token 已失效
          console.error('获取用户信息失败:', error)

          // 防止重复显示错误消息
          if (!isShowingAuthError) {
            isShowingAuthError = true
            ElMessage.error('登录已过期，请重新登录')
            setTimeout(() => {
              isShowingAuthError = false
            }, 3000)
          }

          await userStore.logout()
          next(`/login?redirect=${to.path}`)
        }
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 在白名单中，直接放行
      next()
    } else {
      // 不在白名单中，跳转到登录页，并保存原始路径用于登录后跳转
      // 只在不是来自登录页的情况下显示提示
      if (from.path !== '/login' && !isShowingAuthError) {
        isShowingAuthError = true
        ElMessage.warning('请先登录')
        setTimeout(() => {
          isShowingAuthError = false
        }, 3000)
      }
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
